package com.qfedu.microcoupon.coupon.consumer;

import com.alibaba.fastjson.JSON;
import com.qfedu.common.mq.dto.RegisterDTO;
import com.qfedu.common.redis.utils.RedisCache;
import com.qfedu.microcoupon.coupon.service.CouponInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Classname CouponConsumer
 * @Description TODO
 * @Date 2025-09-30 9:26
 * @Created by 老任与码
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "topic_register",
        consumeTimeout = 1L, // 消费的超时时间，默认15分钟
        maxReconsumeTimes = 1, // 重试次数
        consumerGroup = "coupon_group")
public class CouponConsumer implements RocketMQListener<String> {

    @Resource
    private CouponInfoService couponInfoService;

    @Resource
    private RedisCache redisCache;

    @Override
    public void onMessage(String s) {
        log.info("接受消息：" + s);
        RegisterDTO registerDTO = JSON.parseObject(s, RegisterDTO.class);

        // 如果key不存在，认为还没有消费，增加key，并设置过期时间;如果存在，认为已经消费过了，直接返回
        Boolean ret = redisCache.hasKey("register:retry:" + registerDTO.getUid());
        if (ret) {
            return;
        } else {
            redisCache.setCacheObject("register:retry:" + registerDTO.getUid(), 1, 3600, TimeUnit.SECONDS);
        }

        try {
            Thread.sleep(140000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        try {
            couponInfoService.distributeCoupon(registerDTO.getProductType().getType(), registerDTO.getUid());
        } catch (Exception e) {
            // 将数据写入数据补偿表,通过定时器扫描进行处理，一般也要设置最大重试次数
            // throw new RuntimeException(e);
        }
    }
}
